package com.retail.common.entity;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 分页查询参数基类
 *
 * @author retail
 * @since 2024-01-01
 */
@Data
public class BasePageQuery implements Serializable {

  private static final long serialVersionUID = 1L;

  /**
   * 页码
   */
  @NotNull(message = "页码不能为空")
  @Min(value = 1, message = "页码不能小于1")
  private Long pageNum = 1L;

  /**
   * 每页大小
   */
  @NotNull(message = "每页大小不能为空")
  @Min(value = 1, message = "每页大小不能小于1")
  @Max(value = 100, message = "每页大小不能大于100")
  private Long pageSize = 10L;

  /**
   * 排序字段
   */
  private String orderBy;

  /**
   * 排序方向（asc/desc）
   */
  private String orderDirection = "desc";

  /**
   * 转换为MyBatis Plus分页对象
   */
  public <T> Page<T> toPage() {
    Page<T> page = new Page<>(pageNum, pageSize);
    if (orderBy != null && !orderBy.trim().isEmpty()) {
      boolean isAsc = "asc".equalsIgnoreCase(orderDirection);
      if (isAsc) {
        page.addOrder(com.baomidou.mybatisplus.core.metadata.OrderItem.asc(orderBy));
      } else {
        page.addOrder(com.baomidou.mybatisplus.core.metadata.OrderItem.desc(orderBy));
      }
    }
    return page;
  }
}
